#coding=utf-8
'''
Created on 2017-7-15

@author:  sandy
'''
from twisted.internet import task
import logging
import time
import CenterBuild
from pycommon import Const

import GateFactory

class CenterCtx(object):
    def __init__(self):
        self.uid = 0
        self.gatesid = 0
        self.maxRound = 0
        self.tableModel = 0
        self.playModel = 0
        self.cardId = 0
        self.cardNum = 0
        self.hallId = 0
        self.tableIdStr = ""
        self.time = 0
        
class CenterCtxManager():
    
    def __init__(self):
        self.__idlist = []
        self.__pmap = {}
        

    def start(self, checkinterval=3):
        for i in range(65530):
            self.__idlist.append(i)
        l = task.LoopingCall(self.onTimer)
        l.start(checkinterval, False)

    def onTimer(self):
        popList = []
        for key in self.__pmap:
            ct = self.__pmap.get(key)
            if time.time() - ct.time >= 10:
                popList.append(key)
        for key in popList:
            ct = self.__pmap.pop(key)
            self.__idlist.append(key)
            gate = GateFactory.instance.getGateSrvBySid(ct.gatesid)
            gate.transPkt2Client(ct.uid, CenterBuild.sendCreateTableToClient(Const.ERR_MJ_CREATETABLE_GS_BUSY,""))
            logging.warn(u"uid=%d createTable game->center not return data",ct.uid)
        
    def addCtx(self,uid,gatesid,maxRound,tableModel,playModel,cardId,cardNum,hallId,tableIdStr):
        ctx = CenterCtx()
        ctx.uid = uid
        ctx.gatesid = gatesid
        ctx.maxRound = maxRound
        ctx.tableModel = tableModel
        ctx.playModel = playModel
        ctx.cardId = cardId
        ctx.cardNum = cardNum
        ctx.hallId = hallId
        ctx.tableIdStr = tableIdStr
        ctx.time = time.time()

        id = self.__idlist.pop(0)
        self.__pmap[id] = ctx
        return id
        
    def popCtx(self, id):
        ctx = self.__pmap.pop(id, None)
        if ctx != None:
            self.__idlist.append(id)
            logging.debug(u"popCtx sucess id=%d",id)
        else:
            logging.debug(u"popCtx failed id=%d",id)
        return ctx
        
        
instance = CenterCtxManager()

if __name__ == '__main__':
    pass